<?php
defined( '_JEXEC' ) or die( 'Restricted access' );

//TODO: when url has a trailing / then it can not find any page, do somthing about it.
// 

class Bootstrap {
    function __construct() {
        $url = isset($_GET['url']) ? $_GET['url'] : null;
        $url = rtrim($url, '/');
        $url = filter_var($url, FILTER_SANITIZE_URL);
        $url = explode('/', $url);
        
        if (empty($url[0])) {
            require_once CONTROLLERS.'index.php';
            $controller = new Index();
            $controller->index();
            return false;
        }

        $file = CONTROLLERS . $url[0] . '.php';
        if (file_exists($file)) {
            require_once $file;
        } else {
            $this->error();
            return false;
        }

        $controller = new $url[0];
        $controller->loadModel($url[0]);

        // calling methods
        if (isset($url[2])) {
            if (method_exists($controller, $url[1])) {
                $controller->{$url[1]}($url[2]);
            } else {
                $this->error();
                return false;
            }
        } else {
            if (isset($url[1])) {
                if (method_exists($controller, $url[1])) {
                    $controller->{$url[1]}();
                } else {
                    $this->error();
                    return false;
                }
            } else {
                $controller->index();
            }
        }
    }

    function error() {
        require_once CONTROLLERS.'error.php';
        $controller = new Error();
        $controller->index();
        return false;
    }

}